﻿

goog.provide('ol.dmp.interactionGeometry.Polygon');


goog.require('ol.dmp.interactionGeometry.Base');


ol.dmp.interactionGeometry.Polygon = function (options)
{
    this.minPointsPerSketch = 3;
    goog.base(this, options);
}

goog.inherits(ol.dmp.interactionGeometry.Polygon, ol.dmp.interactionGeometry.Base);



ol.dmp.interactionGeometry.Polygon.prototype.atFinish = function (event)
{
    var potentiallyDone = this.keyPoints_.length > this.minPointsPerSketch;
    var at = false;
    if (potentiallyDone)
    {
        potentiallyFinishCoordinates = [this.keyPoints_[0],this.keyPoints_[this.keyPoints_.length - 1]];
        var map = event.map;
        for (var i = 0, ii = potentiallyFinishCoordinates.length; i < ii; i++)
        {
            var finishCoordinate = potentiallyFinishCoordinates[i];
            var finishPixel = map.getPixelFromCoordinate(finishCoordinate);
            var pixel = event.pixel;
            var dx = pixel[0] - finishPixel[0];
            var dy = pixel[1] - finishPixel[1];
            at = Math.sqrt(dx * dx + dy * dy) <= this.snapTolerance_;
            if (at)
            {
                this.finishCoordinate_ = finishCoordinate;
                break;
            }
        }
    }

    return at;
};



ol.dmp.interactionGeometry.Polygon.prototype.startDrawing = function (event)
{
    var start = event.coordinate;
    this.finishCoordinate_ = start;
    this.keyPoints_.push(start);

    var polygonPoints = [this.keyPoints_.slice()];
    geometry = new ol.geom.Polygon(polygonPoints);
    this.sketchFeature_ = new ol.Feature();
    this.sketchFeature_.setGeometry(geometry);

    var linePoints = this.keyPoints_.slice();
    this.sketchLine_ = new ol.Feature(new ol.geom.LineString(linePoints));

};

ol.dmp.interactionGeometry.Polygon.prototype.modifyDrawing = function (event)
{
    var coordinate = event.coordinate;
    var geometry = this.sketchFeature_.getGeometry();

    var polygonPoints = this.keyPoints_.slice();
    polygonPoints.push(coordinate);
    geometry.setCoordinates([polygonPoints], ol.geom.GeometryLayout.XY);

    var sketchLineGeom = this.sketchLine_.getGeometry();
    var linePoints = this.keyPoints_.slice();
    linePoints.push(coordinate);
    linePoints.push(this.finishCoordinate_);
    sketchLineGeom.setCoordinates(linePoints);
};

ol.dmp.interactionGeometry.Polygon.prototype.addToDrawing = function (event)
{
    var coordinate = event.coordinate;
    var geometry = this.sketchFeature_.getGeometry();

    this.keyPoints_.push(coordinate);
    var polygonPoints = this.keyPoints_.slice();
    polygonPoints.push(coordinate);
    geometry.setCoordinates([polygonPoints], ol.geom.GeometryLayout.XY);
};